/**
 * 心灵树洞 - 前端交互脚本
 * 处理表单提交、字符计数、模态框显示等功能
 */

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

/**
 * 初始化应用
 */
function initializeApp() {
    console.log('心灵树洞应用初始化中...');
    
    // 获取DOM元素
    const form = document.getElementById('messageForm');
    const textarea = document.getElementById('messageContent');
    const charCount = document.getElementById('charCount');
    const submitBtn = document.getElementById('submitBtn');
    const successModal = document.getElementById('successModal');
    const errorModal = document.getElementById('errorModal');
    const closeModalBtn = document.getElementById('closeModal');
    const closeErrorModalBtn = document.getElementById('closeErrorModal');
    
    // 检查必要元素是否存在
    if (!form || !textarea || !charCount || !submitBtn) {
        console.error('关键DOM元素未找到');
        return;
    }
    
    // 初始化字符计数
    updateCharCount();
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 添加输入验证
    addInputValidation();
    
    console.log('应用初始化完成');
}

/**
 * 绑定事件监听器
 */
function bindEventListeners() {
    const form = document.getElementById('messageForm');
    const textarea = document.getElementById('messageContent');
    const closeModalBtn = document.getElementById('closeModal');
    const closeErrorModalBtn = document.getElementById('closeErrorModal');
    
    // 表单提交事件
    form.addEventListener('submit', handleFormSubmit);
    
    // 文本输入事件（实时字符计数）
    textarea.addEventListener('input', updateCharCount);
    textarea.addEventListener('paste', function() {
        // 粘贴后稍微延迟更新计数，确保内容已粘贴
        setTimeout(updateCharCount, 10);
    });
    
    // 模态框关闭事件
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', closeSuccessModal);
    }
    
    if (closeErrorModalBtn) {
        closeErrorModalBtn.addEventListener('click', closeErrorModal);
    }
    
    // 点击模态框背景关闭
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal')) {
            closeAllModals();
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeAllModals();
        }
    });
}

/**
 * 添加输入验证
 */
function addInputValidation() {
    const textarea = document.getElementById('messageContent');
    const categoryInputs = document.querySelectorAll('input[name="category"]');
    
    // 文本框失去焦点时验证
    textarea.addEventListener('blur', function() {
        validateContent();
    });
    
    // 分类选择验证
    categoryInputs.forEach(input => {
        input.addEventListener('change', function() {
            validateCategory();
        });
    });
}

/**
 * 更新字符计数
 */
function updateCharCount() {
    const textarea = document.getElementById('messageContent');
    const charCount = document.getElementById('charCount');
    
    if (!textarea || !charCount) return;
    
    const currentLength = textarea.value.length;
    const maxLength = 2000;
    
    charCount.textContent = currentLength;
    
    // 根据字符数量改变颜色
    if (currentLength > maxLength * 0.9) {
        charCount.style.color = '#e74c3c'; // 红色警告
    } else if (currentLength > maxLength * 0.7) {
        charCount.style.color = '#f39c12'; // 橙色提醒
    } else {
        charCount.style.color = '#27ae60'; // 绿色正常
    }
    
    // 超出限制时禁用提交按钮
    const submitBtn = document.getElementById('submitBtn');
    if (submitBtn) {
        if (currentLength > maxLength) {
            submitBtn.disabled = true;
            submitBtn.style.opacity = '0.5';
        } else {
            submitBtn.disabled = false;
            submitBtn.style.opacity = '1';
        }
    }
}

/**
 * 验证内容
 */
function validateContent() {
    const textarea = document.getElementById('messageContent');
    const content = textarea.value.trim();
    
    if (content.length === 0) {
        showFieldError(textarea, '请输入你想倾诉的内容');
        return false;
    }
    
    if (content.length < 10) {
        showFieldError(textarea, '内容太短了，请多说一些吧');
        return false;
    }
    
    if (content.length > 2000) {
        showFieldError(textarea, '内容超出限制，请适当精简');
        return false;
    }
    
    clearFieldError(textarea);
    return true;
}

/**
 * 验证分类选择
 */
function validateCategory() {
    const categoryInputs = document.querySelectorAll('input[name="category"]');
    const isSelected = Array.from(categoryInputs).some(input => input.checked);
    
    if (!isSelected) {
        showCategoryError('请选择一个问题分类');
        return false;
    }
    
    clearCategoryError();
    return true;
}

/**
 * 显示字段错误
 */
function showFieldError(field, message) {
    clearFieldError(field);
    
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.textContent = message;
    errorDiv.style.color = '#e74c3c';
    errorDiv.style.fontSize = '0.9em';
    errorDiv.style.marginTop = '5px';
    
    field.parentNode.appendChild(errorDiv);
    field.style.borderColor = '#e74c3c';
}

/**
 * 清除字段错误
 */
function clearFieldError(field) {
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    field.style.borderColor = '';
}

/**
 * 显示分类错误
 */
function showCategoryError(message) {
    clearCategoryError();
    
    const categorySection = document.querySelector('.category-section');
    const errorDiv = document.createElement('div');
    errorDiv.className = 'category-error';
    errorDiv.textContent = message;
    errorDiv.style.color = '#e74c3c';
    errorDiv.style.fontSize = '0.9em';
    errorDiv.style.marginTop = '10px';
    
    categorySection.appendChild(errorDiv);
}

/**
 * 清除分类错误
 */
function clearCategoryError() {
    const existingError = document.querySelector('.category-error');
    if (existingError) {
        existingError.remove();
    }
}

/**
 * 处理表单提交
 */
async function handleFormSubmit(event) {
    event.preventDefault();
    
    console.log('开始处理表单提交...');
    
    // 验证表单
    const isContentValid = validateContent();
    const isCategoryValid = validateCategory();
    
    if (!isContentValid || !isCategoryValid) {
        console.log('表单验证失败');
        return;
    }
    
    // 获取表单数据
    const formData = getFormData();
    if (!formData) {
        console.error('获取表单数据失败');
        return;
    }
    
    // 显示提交状态
    setSubmitState(true);
    
    try {
        // 发送请求
        const response = await submitMessage(formData);
        
        if (response.success) {
            console.log('提交成功');
            showSuccessModal(response.message);
            resetForm();
        } else {
            console.error('提交失败:', response.message);
            showErrorModal(response.message);
        }
    } catch (error) {
        console.error('网络请求失败:', error);
        showErrorModal('网络连接异常，请检查网络后重试');
    } finally {
        setSubmitState(false);
    }
}

/**
 * 获取表单数据
 */
function getFormData() {
    const textarea = document.getElementById('messageContent');
    const categoryInputs = document.querySelectorAll('input[name="category"]:checked');
    
    if (!textarea || categoryInputs.length === 0) {
        return null;
    }
    
    return {
        content: textarea.value.trim(),
        category: categoryInputs[0].value
    };
}

/**
 * 提交消息到服务器
 */
async function submitMessage(data) {
    const response = await fetch('/submit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    });
    
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    return await response.json();
}

/**
 * 设置提交状态
 */
function setSubmitState(isSubmitting) {
    const submitBtn = document.getElementById('submitBtn');
    const btnText = submitBtn.querySelector('.btn-text');
    const btnLoading = submitBtn.querySelector('.btn-loading');
    
    if (isSubmitting) {
        submitBtn.disabled = true;
        btnText.style.display = 'none';
        btnLoading.style.display = 'inline';
        submitBtn.style.opacity = '0.7';
    } else {
        submitBtn.disabled = false;
        btnText.style.display = 'inline';
        btnLoading.style.display = 'none';
        submitBtn.style.opacity = '1';
    }
}

/**
 * 重置表单
 */
function resetForm() {
    const form = document.getElementById('messageForm');
    const textarea = document.getElementById('messageContent');
    
    // 重置表单
    form.reset();
    
    // 更新字符计数
    updateCharCount();
    
    // 清除所有错误信息
    clearFieldError(textarea);
    clearCategoryError();
    
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' });
    
    console.log('表单已重置');
}

/**
 * 显示成功模态框
 */
function showSuccessModal(message) {
    const modal = document.getElementById('successModal');
    const messageElement = document.getElementById('successMessage');
    
    if (modal && messageElement) {
        messageElement.textContent = message || '你的声音我们已收到，愿你心情阳光灿烂！';
        modal.style.display = 'flex';
        
        // 添加动画效果
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
    }
}

/**
 * 显示错误模态框
 */
function showErrorModal(message) {
    const modal = document.getElementById('errorModal');
    const messageElement = document.getElementById('errorMessage');
    
    if (modal && messageElement) {
        messageElement.textContent = message || '提交失败，请稍后重试';
        modal.style.display = 'flex';
        
        // 添加动画效果
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
    }
}

/**
 * 关闭成功模态框
 */
function closeSuccessModal() {
    const modal = document.getElementById('successModal');
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
    }
}

/**
 * 关闭错误模态框
 */
function closeErrorModal() {
    const modal = document.getElementById('errorModal');
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
    }
}

/**
 * 关闭所有模态框
 */
function closeAllModals() {
    closeSuccessModal();
    closeErrorModal();
}

/**
 * 工具函数：防抖
 */
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 导出函数供其他脚本使用（如果需要）
window.HeartHole = {
    updateCharCount,
    validateContent,
    validateCategory,
    showSuccessModal,
    showErrorModal,
    closeAllModals
};